package com.banyuan.servlet.opus;

import com.alibaba.fastjson.JSON;
import com.banyuan.dao.OpusDao;
import com.banyuan.domain.Opus;
import com.banyuan.domain.ResData;
import com.banyuan.utils.AuthorUtils;
import com.banyuan.utils.DBUtils;
import com.banyuan.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.DataBufferUShort;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/opus/delete")
public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");


        // 通过传进来的id去查询authorid，在和session里面的authorid是否一样，不一样的话就return
        Integer loginId = AuthorUtils.getLoginId(req);
        ResultSet resultSet = null;
        try {
            resultSet = OpusDao.selectOpusById(Integer.parseInt(id));
            Opus opus = DBUtils.resultToBeanOne(resultSet, Opus.class);
            if (!opus.getAuthorId().equals(loginId)) {
                ResData resData = new ResData(10001,"不能删除他人的书本",null);
                resp.getWriter().write(JSON.toJSONString(resData));
                return;
            }


            // 根据书本id去删除这个id的书本所有信息
            int i = OpusDao.deleteById(Integer.parseInt(id));
            if (i > 0) {
                ResData resData = new ResData(200,"删除成功",null);
                resp.getWriter().write(JSON.toJSONString(resData));
            } else {
                ResData resData = new ResData(10002,"删除失败",null);
                resp.getWriter().write(JSON.toJSONString(resData));
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.closeBy(resultSet);
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
